<template>
  <div>
    <!-- 标题 -->
    <van-nav-bar title="黑马头条" />
    <!-- 登录框 -->
    <div>
      <van-form @submit="onSubmit" @failed="onFailed">
        <van-field
          v-model.trim="user.mobile"
          name="手机号"
          label="手机号"
          placeholder="手机号"
          :rules="[{ pattern: /^1\d{10}$/, message: '手机号输入不正确' }]"
        />
        <van-field
          v-model.trim="user.code"
          type="password"
          name="验证码"
          label="验证码"
          placeholder="验证码"
          :rules="[{ pattern: /^\d{6}$/, message: '验证码错误' }]"
        />
        <div style="margin: 16px" class="btn-wrap">
          <van-button class="van-button" block type="info" native-type="submit"
            >提交</van-button
          >
        </div>
      </van-form>
    </div>
  </div>
</template>

<script>
// import { login, getInfo } from '@/api/user'
export default {
  name: 'login',
  data () {
    return {
      user: {
        mobile: '13800000002',
        code: '246810'
      }
    }
  },
  methods: {
    async doLogin () {
      this.$toast.loading({
        duration: 0, // 持续展示 toast,永远不会关闭，它会被后续的toast覆盖
        overlay: true, // 整体添加一个遮罩
        message: '登陆中...'
      })
      try {
        await this.$store.dispatch('userLogin', this.user)
        await this.$store.dispatch('user/getInfo')
        this.$toast.success('成功')
        // 用户跳转
        // 根据当前路由参数，决定调到哪里
        const backto = this.$route.query.backto || '/'
        this.$router.push(backto)
      } catch (err) {
        console.log(err)
        this.$toast.fail('失败')
      }
    },

    onSubmit () {
      this.doLogin()
    },
    onFailed () {
      console.log('失败')
    }
  }

}
</script>

<style lang="less" scoped>
// 按钮
.btn-wrap {
  padding: 20px;
  .van-button {
    width: 100%;
    background-color: #6db4fd;
    color: #fff;
  }
}
</style>
